//
//  TripsDetailViewController.m
//  chanyou
//
//  Created by leon on 14/12/31.
//  Copyright (c) 2014年 wanli. All rights reserved.
//
#import <ShareSDK/ShareSDK.h>
#import "TripsDetailViewController.h"
#import "ConnectModel.h"
#import "UIImageView+WebCache.h"
#import "TripsModel.h"
#import "TripsDetailModel.h"
#import "TripsDetailTableViewCell.h"
#import "TripsDetailPhotoTableViewCell.h"
#import "TripsDetailPicOnlyTableViewCell.h"
#import "AttractionsViewController.h"
#import "Singleton.h"
#import "LoginViewController.h"
#import "TripsDatabase.h"
#import "SDImageCache.h"
#import "OneDayCellModel.h"
#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)


@interface TripsDetailViewController ()<UITableViewDataSource, UITableViewDelegate,ISSShareViewDelegate>



@end

@implementation TripsDetailViewController

- (void)dealloc
{
    
    NSLog(@"dealloc detail");
    [_imgView release];
    [_userView release];
    [_dateLabel release];
    [_nameLabel release];
    [_userNameLabel release];
    [_detailTableArray release];
    [_detailTableView release];
    [_dayList release];
    [_destinationId release];
    [_tripsArray release];
    [_userName release];
    [_button release];
    [_date release];
    [_name release];
    [_userStr release];
    [_imgStr release];
    [_trips release];
    [_tripsDetail release];
    [_alertCollection release];
    [_reloadImg release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.detailTableArray = [NSMutableArray array];
        self.tripsArray = [NSMutableArray array];
        self.dayList = [NSMutableArray array];
        self.IdNum = 0;
        self.destinationId = [NSString string];
        self.totalDay = [NSMutableArray array];
        self.oneDay = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigation_bar_background.png"] forBarMetrics:UIBarMetricsDefault];
//    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-back.png"] style:UIBarButtonItemStyleDone target:self action:@selector(backAction)];
    // navigation的title
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 45, 100)];
    label.textColor = [UIColor colorWithRed:255 / 255.0 green:69 / 255.0 blue:0 alpha:1];
    label.font = [UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:20];
    label.text = @"游记";
    self.navigationItem.titleView = label;

    NSString *leftPath = [[NSBundle mainBundle] pathForResource:@"iconfont-back" ofType:@".png"];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[[[UIImage alloc] initWithContentsOfFile:leftPath] autorelease] style:UIBarButtonItemStyleDone target:self action:@selector(backAction)] autorelease];

    
    // bar上的分享与收藏按钮
    UIBarButtonItem *collectButton = [[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-shoucang1-2.png"] style:UIBarButtonItemStylePlain target:self action:@selector(collectAction:)]autorelease];
    UIButton *share = [[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)] autorelease];
//    share.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:69 / 255.0 blue:0 alpha:1];
    
    [share setImage:[UIImage imageNamed:@"iconfont-share.png"] forState:UIControlStateNormal];
    [share addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *shareButton = [[UIBarButtonItem alloc] initWithCustomView:share];
    
    [self.navigationItem setRightBarButtonItems:[NSMutableArray arrayWithObjects:collectButton, shareButton, nil] animated:YES];
    
    
    
    [self startConnect];
    
    [self createView];
}
- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
//    [[SDImageCache sharedImageCache] clearMemory];
}
#pragma mark -
#pragma mark 分享
- (void)shareAction:(id)sender
{
    Singleton *share = [Singleton shareInstance];
    share.loginDefault = [NSUserDefaults standardUserDefaults];
    if ([[share.loginDefault objectForKey:@"登陆状态"] isEqualToString:@"yes"] || share.logined == YES) {
        
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"ShareSDK" ofType:@"png"];
    //构造分享内容
    NSString *str = [_connectStr stringByReplacingOccurrencesOfString:@"/api" withString:@""];
    str = [str stringByReplacingOccurrencesOfString:@".json" withString:@""];
    
    id<ISSContent> publishContent = [ShareSDK content:[NSString stringWithFormat:@"我在这里看到一篇游记#%@#,%@", _name, str] defaultContent:@"测试一下"image:[ShareSDK imageWithPath:imagePath]title:@"ShareSDK" url:@"http://www.mob.com" description:@"这是一条测试信息" mediaType: SSPublishContentMediaTypeNews];
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    [container setIPadContainerWithView:sender arrowDirect:UIPopoverArrowDirectionUp];
    [container setIPhoneContainerWithViewController:self];
    //自定义标题栏相关委托
    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES
                                                         allowCallback:NO
                                                         authViewStyle:SSAuthViewStyleFullScreenPopup
                                                          viewDelegate:nil
                                               authManagerViewDelegate:nil];
    //自定义标题栏相关委托
    id<ISSShareOptions> shareOptions = [ShareSDK defaultShareOptionsWithTitle:@"分享"
                                                              oneKeyShareList:[NSArray defaultOneKeyShareList]
                                                               qqButtonHidden:YES
                                                        wxSessionButtonHidden:YES
                                                       wxTimelineButtonHidden:YES
                                                         showKeyboardOnAppear:NO
                                                            shareViewDelegate:self
                                                          friendsViewDelegate:nil
                                                        picViewerViewDelegate:nil];

    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:authOptions
                      shareOptions:shareOptions
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                if (state == SSResponseStateSuccess)
                                {
                                    _alert = [[UIAlertView alloc] initWithTitle:@"分享成功" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                                    [_alert show];
                                    [NSTimer scheduledTimerWithTimeInterval:1.2f target:self selector:@selector(alertAction:) userInfo:nil repeats:YES];
                                    
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    _alert = [[UIAlertView alloc] initWithTitle:@"分享失败" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                                    [_alert show];
                                    [NSTimer scheduledTimerWithTimeInterval:1.2f target:self selector:@selector(alertAction:) userInfo:nil repeats:YES];
                                }
                            }];
    } else {
        self.alterLogin = [[UIAlertView alloc] initWithTitle:@"请先登陆后尝试。" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [_alterLogin show];
        [NSTimer scheduledTimerWithTimeInterval:1.2f target:self selector:@selector(alterLoginAction:) userInfo:nil repeats:YES];
        
        LoginViewController *login = [[LoginViewController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:login];
        nav.navigationBar.translucent = YES;
        NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIColor redColor] forKey:NSForegroundColorAttributeName];
        nav.navigationBar.titleTextAttributes = dic;
        [self presentViewController:nav animated:YES completion:nil];
        [nav release];
        [login release];
    }
}


- (void)alertAction:(id)sender
{
    [_alert dismissWithClickedButtonIndex:1 animated:YES];
}

- (void)alterLoginAction:(id)sender
{
    [_alterLogin dismissWithClickedButtonIndex:1 animated:YES];
}

#pragma mark - ISSShareViewDelegate
- (void)viewOnWillDisplay:(UIViewController *)viewController shareType:(ShareType)shareType

{
    
    //修改分享编辑框的标题栏颜色
    viewController.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:255 / 255.0 green:69 / 255.0 blue:0 alpha:1];
    
    //将分享编辑框的标题栏替换为图片
    //    UIImage *image = [UIImage imageNamed:@"iPhoneNavigationBarBG.png"];
    //    [viewController.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    
}

#pragma mark -
#pragma mark 收藏
- (void)collectAction:(UIButton *)button
{
//    NSLog(@"self 33333 === %d", [self retainCount]);
    Singleton *share = [Singleton shareInstance];
    if ((share.logined == NO || [[share.loginDefault objectForKey:@"登陆状态"] isEqualToString:@"no"])) {
        self.alertCollection = [[UIAlertView alloc] initWithTitle:nil message:@"请先登录后操作" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [_alertCollection show];
        [NSTimer scheduledTimerWithTimeInterval:1.2f target:self selector:@selector(alertCollectionAction:) userInfo:nil repeats:YES];
        
        LoginViewController *loginView = [[[LoginViewController alloc] init] autorelease];
        UINavigationController *nav = [[[UINavigationController alloc] initWithRootViewController:loginView] autorelease];
        nav.navigationBar.translucent = YES;
        NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIColor redColor] forKey:NSForegroundColorAttributeName];
        nav.navigationBar.titleTextAttributes = dic;

        [self.navigationController presentViewController:nav animated:YES completion:nil];
//        [loginView release];
//        [nav release];
        
    } else {
        BOOL insertJudge = [TripsDatabase insertIntoTravelWithTripsModel:_trips];
        if (insertJudge == YES) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
        } else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该游记已经被收藏过!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];

        }
    }
}

- (void)alertCollectionAction:(id)sender
{
    [_alertCollection dismissWithClickedButtonIndex:1 animated:YES];
}

- (void)viewDidAppear:(BOOL)animated
{
     NSLog(@"self retain count = %ld", [self retainCount]);
}

#pragma mark-
#pragma mark 网络请求并获得数据
- (void)startConnect{
    self.connectStr = [NSString stringWithFormat:@"http://chanyouji.com/api/trips/%ld.json",_IdNum];
    
    __block  TripsDetailViewController *detail = self;

//    NSLog(@"detail retain count = %d", [detail retainCount]);
    [ConnectModel connectModelWithUrl:_connectStr parmaters:nil finished:^(NSData *data) {

        [_reloadImg removeFromSuperview];
        
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        detail.detailTableArray = [dic objectForKey:@"trip_days"];
//        NSLog(@"detail retain count = %d", [detail retainCount]);
        for (NSDictionary *dic in detail.detailTableArray) {
            NSString *str = [NSString stringWithFormat:@"%@", [dic objectForKey:@"day"]];
            [detail.dayList addObject: str];
            
            NSArray *nodesArray = [dic objectForKey:@"nodes"];
//            NSInteger count = 0;
            NSMutableArray *oneDayCell = [NSMutableArray array];
            for (NSDictionary *nodesDic in nodesArray) {
                NSArray *notesArray = [nodesDic objectForKey:@"notes"];
                
//                count += notesArray.count;
                for (NSDictionary *dic in notesArray) {
                    OneDayCellModel *one = [[OneDayCellModel alloc]init];
                    one.des = [dic objectForKey:@"description"];
                    NSDictionary *photoDic = [dic objectForKey:@"photo"];
                    if (photoDic != nil) {
                        one.url = [photoDic objectForKey:@"url"];
                    }
                    [oneDayCell addObject:one];
                }
            }
            [detail.totalDay addObject:oneDayCell];
            
        }
        detail.imgStr = [dic objectForKey:@"front_cover_photo_url"];
        detail.name = [dic objectForKey:@"name"];
        detail.userName = [[dic objectForKey:@"user"] objectForKey:@"name"];
        detail.userStr = [[dic objectForKey:@"user"] objectForKey:@"image"];
        detail.date = [dic objectForKey:@"start_date"];
        [detail createTableHeader];
        [detail.detailTableView reloadData];
    }];
}



#pragma mark - 
#pragma mark 创建tableView
- (void)createView
{
    self.detailTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, SCREEN_HEIGHT - 64)];
    _detailTableView.dataSource = self;
    _detailTableView.delegate = self;
 
    _detailTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // 1
    [_detailTableView registerClass:[TripsDetailTableViewCell class] forCellReuseIdentifier:@"tripDetailCell"];
    // 2
    [_detailTableView registerClass:[TripsDetailPhotoTableViewCell class] forCellReuseIdentifier:@"tripsDetailPhotoCell"];
    // 3
    [_detailTableView registerClass:[TripsDetailPicOnlyTableViewCell class] forCellReuseIdentifier:@"tripsDetailPicOnly"];
    [self.view addSubview:_detailTableView];
    [_detailTableView release];
    
    
    // 风火轮
    self.reloadImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"reload.png"]];
    _reloadImg.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2 - 64);
    // _reloadImg.clipsToBounds = YES;
    [self.view addSubview:_reloadImg];
    [_reloadImg release];
    
    CABasicAnimation *rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2.0];
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    rotationAnimation.duration = 2;
    rotationAnimation.repeatCount = 10000;
    rotationAnimation.cumulative = NO;
    rotationAnimation.removedOnCompletion = NO;
    rotationAnimation.fillMode = kCAFillModeForwards;
    [_reloadImg.layer addAnimation:rotationAnimation forKey:@"rotation"];

}

- (void)createTableHeader
{
    NSString *placeHolder = [[NSBundle mainBundle] pathForResource:@"placeHold.png" ofType:nil];
    // tableView的header
    self.detailTableView.tableHeaderView = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 3)] autorelease];
    // 背景图片
    self.imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 3)];
    [_imgView sd_setImageWithURL:[NSURL URLWithString:self.imgStr] placeholderImage:[[[UIImage alloc] initWithContentsOfFile:placeHolder] autorelease]];
    [self.detailTableView addSubview:_imgView];
    [_imgView release];
    
    // 用户头像
    self.userView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 20, self.view.frame.size.height / 6, self.view.frame.size.width / 7, self.view.frame.size.width / 7)];
    [_userView sd_setImageWithURL:[NSURL URLWithString:self.userStr ]placeholderImage:[UIImage imageWithContentsOfFile:placeHolder]];
    _userView.layer.masksToBounds = YES;
    _userView.layer.cornerRadius = self.view.frame.size.width / 14;
    [self.imgView addSubview:_userView];
    [_userView release];
    
    // 标题
    self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 4.5, self.view.frame.size.height / 8, self.view.frame.size.width / 1.3, self.view.frame.size.width / 5)];
    _nameLabel.text = self.name;
    [_nameLabel setTextColor:[UIColor whiteColor]];
    _nameLabel.font = [UIFont boldSystemFontOfSize:18];
    _nameLabel.shadowColor = [UIColor lightGrayColor];
    _nameLabel.highlighted = YES;
    [self.imgView addSubview:_nameLabel];
    [_nameLabel release];
    
    //用户名
    self.userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 4.3, self.view.frame.size.height / 6.5, self.view.frame.size.width / 2.0, self.view.frame.size.width / 4)];
    _userNameLabel.text = [NSString stringWithFormat:@"%@%@", @"By ", self.userName];
    [_userNameLabel setTextColor:[UIColor whiteColor]];
    _userNameLabel.font = [UIFont boldSystemFontOfSize:16];
    _userNameLabel.font = [UIFont systemFontOfSize:15];
    _userNameLabel.shadowColor = [UIColor lightGrayColor];
    [self.imgView addSubview:_userNameLabel];
    [_userNameLabel release];
    
    // 日期及天数
    self.dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 4.3, self.view.frame.size.height / 5.0, self.view.frame.size.width / 2, self.view.frame.size.width / 4)];
    NSString *dateStr = [self.date stringByReplacingOccurrencesOfString:@"-" withString:@"."];
    NSInteger daysStr = [_dayList count];
    NSString *dateAndDays = [NSString stringWithFormat:@"%@ | %d天", dateStr, daysStr];
    _dateLabel.text = dateAndDays;
    [_dateLabel setTextColor:[UIColor whiteColor]];
    _dateLabel.font = [UIFont boldSystemFontOfSize:16];
    _dateLabel.font = [UIFont systemFontOfSize:15];
    _dateLabel.shadowColor = [UIColor lightGrayColor];
    [self.imgView addSubview:_dateLabel];
    [_dateLabel release];
    
}

#pragma mark -
#pragma mark UITableView协议
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//    return [_dayList count];
    return [_totalDay count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *str = [NSString stringWithFormat:@"%@%@",@"DAY", _dayList[section]];
    return str;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *days = [_totalDay objectAtIndex:section];
    return [days count];
    
}
//滑动停止时加载图片
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    //获取可见的cell
    NSArray *cellArray = self.detailTableView.visibleCells;
    //获取可见cell的位置
    NSArray *cellRow = self.detailTableView.indexPathsForVisibleRows;
    if ([cellArray count] == 0 || [cellRow count] == 0){
        return;
    }
    
    NSIndexPath *indexPath = [cellRow objectAtIndex:0];
    
    //一个oneDay保存有n个cell, 一个oneModel保存cell的具体内容
    NSArray *oneDay = [self.totalDay objectAtIndex:indexPath.section];
    
    //    NSLog(@"index = %@", cellRow);
    //    NSLog(@"end :cells = %d, rows = %d", [cellArray count], [cellRow count]);
    
    
    SDImageCache *cache = [SDImageCache sharedImageCache];
    NSString *placeHolder = [[NSBundle mainBundle] pathForResource:@"placeHold.png" ofType:nil];
    for (int i = 0; i < [cellArray count] && i < [cellRow count]; i++) {
        //        NSLog(@"i = %d", i);
        //当一天中的cell个数小于可见cell的个数时
        if ([oneDay count] < [cellArray count]) {
            for (int j = 0; j < [oneDay count]; j++) {
                //                NSLog(@"j = %d", j);
                NSIndexPath *indexPath = [cellRow objectAtIndex:j];
                OneDayCellModel *oneModel = [oneDay objectAtIndex:indexPath.row];
                UITableViewCell *cell = [cellArray objectAtIndex:i];
                if ([cell.reuseIdentifier isEqualToString:@"tripDetailCell"]) {
                    continue;
                }else if([cell.reuseIdentifier isEqualToString:@"tripsDetailPhotoCell"]) {
                    TripsDetailPhotoTableViewCell *cell2 = (TripsDetailPhotoTableViewCell *)cell;
                    if ([cache imageFromMemoryCacheForKey:oneModel.url] == nil){
                        
                        [cell2.photoView sd_setImageWithURL:[NSURL URLWithString:oneModel.url] placeholderImage:[UIImage imageWithContentsOfFile:placeHolder]];
                    }
                    cell2.descriptionLabel.text = oneModel.des;
                }else if (@"tripsDetailPicOnly"){
                    if ([cache imageFromMemoryCacheForKey:oneModel.url] == nil){
                        
                        
                        TripsDetailPicOnlyTableViewCell *cell3 = (TripsDetailPicOnlyTableViewCell *)cell;
                        [cell3.photoView sd_setImageWithURL:[NSURL URLWithString:oneModel.url] placeholderImage:[UIImage imageWithContentsOfFile:placeHolder]];
                    }
                }else {
                    break;
                }
            }
            
            //获取下一天的cell
            for (int k = [cellArray count] - [oneDay count]; k < [cellRow count]; k++) {
                //                NSLog(@"k = %d", k);
                oneDay = [self.totalDay objectAtIndex:indexPath.section + 1];
                
                NSIndexPath *indexPath = [cellRow objectAtIndex:i];
                OneDayCellModel *oneModel = [oneDay objectAtIndex:indexPath.row];
                UITableViewCell *cell = [cellArray objectAtIndex:i];
                if ([cell.reuseIdentifier isEqualToString:@"tripDetailCell"]) {
                    continue;
                }else if([cell.reuseIdentifier isEqualToString:@"tripsDetailPhotoCell"]) {
                    TripsDetailPhotoTableViewCell *cell2 = (TripsDetailPhotoTableViewCell *)cell;
                    if ([cache imageFromMemoryCacheForKey:oneModel.url] == nil){
                        
                        [cell2.photoView sd_setImageWithURL:[NSURL URLWithString:oneModel.url] placeholderImage:[UIImage imageWithContentsOfFile:placeHolder]];
                    }
                    cell2.descriptionLabel.text = oneModel.des;
                }else if (@"tripsDetailPicOnly"){
                    if ([cache imageFromMemoryCacheForKey:oneModel.url] == nil){
                        
                        
                        TripsDetailPicOnlyTableViewCell *cell3 = (TripsDetailPicOnlyTableViewCell *)cell;
                        [cell3.photoView sd_setImageWithURL:[NSURL URLWithString:oneModel.url] placeholderImage:[UIImage imageWithContentsOfFile:placeHolder]];
                    }
                }else {
                    break;
                }
            }
        }
        else {
            NSIndexPath *indexPath = [cellRow objectAtIndex:i];
            OneDayCellModel *oneModel = [oneDay objectAtIndex:indexPath.row];
            UITableViewCell *cell = [cellArray objectAtIndex:i];
            //            NSLog(@"des = %@", oneModel.des);
            //            NSLog(@"url = %@", oneModel.url);
            if ([cell.reuseIdentifier isEqualToString:@"tripDetailCell"]) {
                continue;
            }else if([cell.reuseIdentifier isEqualToString:@"tripsDetailPhotoCell"]) {
                TripsDetailPhotoTableViewCell *cell2 = (TripsDetailPhotoTableViewCell *)cell;
                if ([cache imageFromMemoryCacheForKey:oneModel.url] == nil){
                    
                    [cell2.photoView sd_setImageWithURL:[NSURL URLWithString:oneModel.url] placeholderImage:[UIImage imageWithContentsOfFile:placeHolder]];
                }
                //                cell2.descriptionLabel.text = oneModel.des;
            }else if ([cell.reuseIdentifier isEqualToString:@"tripsDetailPicOnly"]){
                if ([cache imageFromMemoryCacheForKey:oneModel.url] == nil){
                    
                    
                    TripsDetailPicOnlyTableViewCell *cell3 = (TripsDetailPicOnlyTableViewCell *)cell;
                    [cell3.photoView sd_setImageWithURL:[NSURL URLWithString:oneModel.url] placeholderImage:[UIImage imageWithContentsOfFile:placeHolder]];
                }
            }else {
                break;
            }
        }
    }
}


//移动停止时加载图片
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    //    decelerate = NO;
    
    NSString *placeHolder = [[NSBundle mainBundle] pathForResource:@"placeHold.png" ofType:nil];
    if (!decelerate) {
        NSLog(@"decelerate = %d", decelerate);
        //获取可见的cell
        NSArray *cellArray = self.detailTableView.visibleCells;
        //获取可见cell的位置
        NSArray *cellRow = self.detailTableView.indexPathsForVisibleRows;
        if ([cellArray count] == 0 || [cellRow count] == 0){
            return;
        }
        
        
        NSIndexPath *indexPath = [cellRow objectAtIndex:0];
        
        
        //一个oneDay保存有n个cell, 一个oneModel保存cell的具体内容
        NSArray *oneDay = [self.totalDay objectAtIndex:indexPath.section];
        
        //    NSLog(@"index = %@", cellRow);
        NSLog(@"dragging :cells = %d, rows = %d", [cellArray count], [cellRow count]);
        
        
        SDImageCache *cache = [SDImageCache sharedImageCache];
        
        for (int i = 0; i < [cellArray count] && i < [cellRow count]; i++) {
            //        NSLog(@"i = %d", i);
            //当一天中的cell个数小于可见cell的个数时
            if ([oneDay count] < [cellArray count]) {
                for (int j = 0; j < [oneDay count]; j++) {
                    //                NSLog(@"j = %d", j);
                    NSIndexPath *indexPath = [cellRow objectAtIndex:j];
                    OneDayCellModel *oneModel = [oneDay objectAtIndex:indexPath.row];
                    UITableViewCell *cell = [cellArray objectAtIndex:i];
                    if ([cell.reuseIdentifier isEqualToString:@"tripDetailCell"]) {
                        continue;
                    }else if([cell.reuseIdentifier isEqualToString:@"tripsDetailPhotoCell"]) {
                        TripsDetailPhotoTableViewCell *cell2 = (TripsDetailPhotoTableViewCell *)cell;
                        if ([cache imageFromMemoryCacheForKey:oneModel.url] == nil){
                            
                            [cell2.photoView sd_setImageWithURL:[NSURL URLWithString:oneModel.url] placeholderImage:[UIImage imageWithContentsOfFile:placeHolder]];
                        }
                        cell2.descriptionLabel.text = oneModel.des;
                    }else if (@"tripsDetailPicOnly"){
                        if ([cache imageFromMemoryCacheForKey:oneModel.url] == nil){
                            
                            
                            TripsDetailPicOnlyTableViewCell *cell3 = (TripsDetailPicOnlyTableViewCell *)cell;
                            [cell3.photoView sd_setImageWithURL:[NSURL URLWithString:oneModel.url] placeholderImage:[UIImage imageWithContentsOfFile:placeHolder]];
                        }
                    }else {
                        break;
                    }
                }
                
                //获取下一天的cell
                for (int k = [cellArray count] - [oneDay count]; k < [cellRow count]; k++) {
                    //                NSLog(@"k = %d", k);
                    oneDay = [self.totalDay objectAtIndex:indexPath.section + 1];
                    
                    NSIndexPath *indexPath = [cellRow objectAtIndex:i];
                    OneDayCellModel *oneModel = [oneDay objectAtIndex:indexPath.row];
                    UITableViewCell *cell = [cellArray objectAtIndex:i];
                    if ([cell.reuseIdentifier isEqualToString:@"tripDetailCell"]) {
                        continue;
                    }else if([cell.reuseIdentifier isEqualToString:@"tripsDetailPhotoCell"]) {
                        TripsDetailPhotoTableViewCell *cell2 = (TripsDetailPhotoTableViewCell *)cell;
                        if ([cache imageFromMemoryCacheForKey:oneModel.url] == nil){
                            
                            [cell2.photoView sd_setImageWithURL:[NSURL URLWithString:oneModel.url] placeholderImage:[UIImage imageWithContentsOfFile:placeHolder]];
                        }
                        cell2.descriptionLabel.text = oneModel.des;
                    }else if (@"tripsDetailPicOnly"){
                        if ([cache imageFromMemoryCacheForKey:oneModel.url] == nil){
                            
                            
                            TripsDetailPicOnlyTableViewCell *cell3 = (TripsDetailPicOnlyTableViewCell *)cell;
                            [cell3.photoView sd_setImageWithURL:[NSURL URLWithString:oneModel.url] placeholderImage:[UIImage imageWithContentsOfFile:placeHolder]];
                        }
                    }else {
                        break;
                    }
                }
            }
            else {
                NSIndexPath *indexPath = [cellRow objectAtIndex:i];
                OneDayCellModel *oneModel = [oneDay objectAtIndex:indexPath.row];
                UITableViewCell *cell = [cellArray objectAtIndex:i];
                //            NSLog(@"des = %@", oneModel.des);
                //            NSLog(@"url = %@", oneModel.url);
                if ([cell.reuseIdentifier isEqualToString:@"tripDetailCell"]) {
                    continue;
                }else if([cell.reuseIdentifier isEqualToString:@"tripsDetailPhotoCell"]) {
                    TripsDetailPhotoTableViewCell *cell2 = (TripsDetailPhotoTableViewCell *)cell;
                    if ([cache imageFromMemoryCacheForKey:oneModel.url] == nil){
                        
                        [cell2.photoView sd_setImageWithURL:[NSURL URLWithString:oneModel.url] placeholderImage:[UIImage imageWithContentsOfFile:placeHolder]];
                    }
                    //                cell2.descriptionLabel.text = oneModel.des;
                }else if ([cell.reuseIdentifier isEqualToString:@"tripsDetailPicOnly"]){
                    if ([cache imageFromMemoryCacheForKey:oneModel.url] == nil){
                        
                        
                        TripsDetailPicOnlyTableViewCell *cell3 = (TripsDetailPicOnlyTableViewCell *)cell;
                        [cell3.photoView sd_setImageWithURL:[NSURL URLWithString:oneModel.url] placeholderImage:[UIImage imageWithContentsOfFile:placeHolder]];
                    }
                }else {
                    break;
                }
            }
        }
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TripsDetailTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:@"tripDetailCell"];
    TripsDetailPhotoTableViewCell *cell2 = [tableView dequeueReusableCellWithIdentifier:@"tripsDetailPhotoCell"];
    TripsDetailPicOnlyTableViewCell *cell3 = [tableView dequeueReusableCellWithIdentifier:@"tripsDetailPicOnly"];
    
    NSArray *oneDay = [self.totalDay objectAtIndex:indexPath.section];
    OneDayCellModel *oneModel = [oneDay objectAtIndex:indexPath.row];
    SDImageCache *cache = [SDImageCache sharedImageCache];
    
    if (oneModel.url == nil) {
        cell1.descriptionLabel.text = oneModel.des;
        return cell1;
    }else if ([oneModel.des isKindOfClass:[NSNull class]]){
        NSString *photoStr = oneModel.url;
        
        cell3.photoView.image = [cache imageFromMemoryCacheForKey:photoStr];
        return cell3;
    }
    else{
        NSString *photoStr = oneModel.url;
        cell2.photoView.image = [cache imageFromMemoryCacheForKey:photoStr];
        
        cell2.descriptionLabel.text = oneModel.des;
        return cell2;
    }
    return cell1;
}


- (void)locationAction:(UIButton *)button
{
    AttractionsViewController *attraction = [[[AttractionsViewController alloc] init] autorelease];
    
    attraction.destination_id = _destinationId;
    [self.navigationController pushViewController:attraction animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *description = @"";

    
    NSArray *oneDay = [_totalDay objectAtIndex:indexPath.section];
    OneDayCellModel *oneModel = [oneDay objectAtIndex:indexPath.row];
    if (oneModel.url == nil) {
        description = oneModel.des;
        NSDictionary *dic  = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14.0f], NSFontAttributeName, nil];
        CGRect rect = [description boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 15, 1000) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:dic context:nil];
        CGFloat height = rect.size.height + 50;
        return height;
    }else if ([oneModel.des isKindOfClass:[NSNull class]]){
      
        return SCREEN_HEIGHT / 3 + 10;
       
    }else{
       
        description = oneModel.des;
        NSDictionary *dic  = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14.0f], NSFontAttributeName, nil];
        CGRect rect = [description boundingRectWithSize:CGSizeMake(self.view.frame.size.width - 15, 1000) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:dic context:nil];
        CGFloat height = rect.size.height + SCREEN_HEIGHT / 3 + 25;
        return height;
        
    }
    return 200.0f;
}



#pragma mark -
#pragma mark 覆盖整个页面的透明View
- (void)createCoverView
{
    self.coverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [_coverView setBackgroundColor:[UIColor redColor]];
    _coverView.alpha = 0;
    [self.view addSubview:_coverView];
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    [[SDImageCache sharedImageCache] clearMemory];

    NSLog(@"wwwwwww");
}

@end
